package com.qf.mybatis01.servlet;

import com.qf.mybatis01.dao.UserDao;
import com.qf.mybatis01.entity.User;
import com.qf.mybatis01.utils.MybatisUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Random;

@WebServlet("/pick")
public class PickServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        UserDao userDao = MybatisUtils.getMapper(UserDao.class);

        final List<User> users = userDao.getAllUnPickedUsers();

        if (users.size()>0){
            // 产生一个随机下标
            final Random random = new Random();
            final int index = random.nextInt(users.size());
            // 选取中奖同学
            final User user = users.get(index);
            // 修改中奖同学的状态 ，把 sex 改为1
            user.setSex("1");
            userDao.updateUser(user);
            MybatisUtils.commit();
            // 返回数据
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().println(user.getName());
        }else {
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().println("抽完了");
        }

    }
}
